
<template>
    <div>
       <van-nav-bar
        title="用户注册"
        left-text="返回"
        left-arrow
        @click-left="goBack"
        />

        <div class="register-panel">
        <van-field
            v-model="username"
            label="用户名"
            icon="clear"
            placeholder="请输入用户名"
            required
            :error-message="usernameErrMsg"
            @click-icon="username = ''"
        />

        <van-field
            v-model="password"
            type="password"
            label="密码"
            placeholder="请输入密码"
            :error-message="passwordErrMsg"
            required
        />
        <div class="register-button">
            <van-button type="primary" :loading="loading" @click="registerAction" size="large">马上注册</van-button>
        </div>
       </div>

    </div>
</template>
<script>
// import axios from 'axios'
// import URL from '@/serverAPI.config'
import {register} from '@/api/user'
export default {
  data () {
    return {
      password: '',
      username: '',
      loading: false, // 是否开启注册请求

      // 错误提示
      passwordErrMsg: '',
      usernameErrMsg: ''
    }
  },
  methods: {
    goBack () {
      this.$router.back()
    },
    checkForm () {
      let flag = true
      if (this.username.length < 2) {
        this.usernameErrMsg = '用户名不能小于 2 位'
        flag = false
      } else {
        this.usernameErrMsg = ''
      }
      if (this.password.length < 5) {
        this.passwordErrMsg = '密码不能小于 5 位'
        flag = false
      } else {
        this.passwordErrMsg = ''
      }
      return flag
    },
    registerUser () {
      this.loading = true
      const data = {password: this.password, username: this.username}
      register(data).then(res => {
        if (res.data.code === 200) {
          this.$toast.success('注册成功')
          this.$router.push({path: '/'})
        } else {
          this.loading = false
          this.$toast.fail('注册失败')
        }
      }).catch(err => {
        console.log(err)
        this.loading = false
        this.$toast.fail('注册失败')
      })
    },
    registerAction () {
      this.checkForm() && this.registerUser()
    }
  }
}
</script>

<style scoped>
    .register-panel{
        width:96%;
        border-radius: 5px;
        margin:20px auto;
        padding-bottom:50px;
    }
    .register-button{
        padding-top:10px;
    }
</style>
